package com.yxkj.sms;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.util.EncodingUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    SmsManager smsManager;
    //    PendingIntent paIntent, deliveryIntent;
    String[] split;
    /**
     * 发送与接收的广播
     **/
    String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
    private SparseArray<String> sendStateList = new SparseArray<>();//发送状态
    private SparseArray<String> receiveList = new SparseArray<>();//发送状态

    private ListView listview;
    private SMSAdapter mAdapter;
    private List<String> datasContent;
    private String message;
    //    private StringBuffer msgLog = new StringBuffer("");
    private String number;
    private TextView result;
    private EditText editText;
    private EditText editText2;
    private Button button;
    private String PATH;
    private int count = 0;
    private ProgressBar progressbar;
    private SmsAsyncTask mAsyncTask;

    private SendAsyncTask sendAsyncTask;

    int sendCount = 0;
    int receiverCount = 0;
    private BroadcastReceiver broadcastSend = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            sendCount++;
            int resultCode = getResultCode();
            int index = intent.getIntExtra("INDEX",-1);
            number = intent.getStringExtra("SEND_SMS_NUM");
            message = intent.getStringExtra("SEND_SMS_CONTENT");
            if (resultCode == Activity.RESULT_OK) {
                Log.i("activity_main", index + "信息发送成功"+ number);
                sendStateList.put(index, "发送成功");
            } else {
                Log.i("activity_main", index + "信息发送失败");
                sendStateList.put(index, "发送失败" + number);
            }
            if (sendCount >= 97) {
                mAdapter.setSendStateList(sendStateList);
                progressbar.setVisibility(View.GONE);
                tvWait.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this, "查询完毕", Toast.LENGTH_SHORT).show();
            }
        }
    };
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            receiverCount++;
            int index = intent.getIntExtra("INDEX",-1);
//            Integer index = Integer.valueOf(sindex);
            Log.i("activity_main", index + "收件人已接收");
            receiveList.put(index, "收件人已接收");
            if (receiverCount >= 97) {
                mAdapter.setReceiveList(receiveList);
                progressbar.setVisibility(View.GONE);
                tvWait.setVisibility(View.GONE);
            }
        }
    };
    private TextView tvWait;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new CommonConfig(MyApplication.Instance()); // 配置类
        initView();
        initSDK();  //
        initsmsManager();

        mAsyncTask = new SmsAsyncTask();
        mAsyncTask.execute();

        button.setOnClickListener(new View.OnClickListener() {//单条发送
            public void onClick(View v) {
                number = editText.getText().toString();
                message = editText2.getText().toString();
                if (!message.isEmpty()) {
                    datasContent.add(number + "***" + message);
                    mAdapter.setDatalist(datasContent);
                }
            }
        });
    }

    private void initsmsManager() {
        smsManager = SmsManager.getDefault();
        //PendingIntent.getBroadcast返回一个用于广播的PendingIntent对象，类似于调用Content.MainActivityBroadcast();
//        paIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent("SMS_SENT2"), 0);
//        deliveryIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent("SMS_DELIVERED2"), 0);

        // 注册一个BroadcastReceiver,当有匹配它的IntentFilter的Intent出现时，该方法会被触发
        registerReceiver(broadcastSend, new IntentFilter(SENT_SMS_ACTION));
//        registerReceiver(broadcastReceiver, new IntentFilter(DELIVERED_SMS_ACTION));
    }

    private void initView() {
        listview = (ListView) findViewById(R.id.listview);
        editText = (EditText) findViewById(R.id.number);
        editText2 = (EditText) findViewById(R.id.message);
        result = (TextView) findViewById(R.id.result);
        button = (Button) findViewById(R.id.button);
        findViewById(R.id.btn_send).setOnClickListener(this);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        tvWait = (TextView) findViewById(R.id.tv_wait);
    }

    private void initSDK() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
                && Environment.getExternalStorageDirectory().canWrite()) {
            // 有访问SDCARD
            File sdCardDir = Environment.getExternalStorageDirectory();
            PATH = sdCardDir.getPath() + "/17phone/";
        } else {
            PATH = "/17phone/";
        }
        // 创建资源根路径
        File file = new File(PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public void getTextData() {
        //将读出来的一行行数据使用Map存储
//        String filePath = "/sdcard/number.txt";//手机上SD
//        String filePath = "file:///android_asset/number.txt";
        String filePath = PATH + "number.txt";
        datasContent = new ArrayList<>();
        if (filePath.contains("asset")) {
            getFromAssets("number.txt");
            return;
        }
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {       //文件存在的前提
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GB2312");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {     //
                    if (!"".equals(lineTxt)) {
                        String temp1 = EncodingUtils.getString(lineTxt.getBytes("utf-8"), "utf-8");
                        String reds = temp1.split("\\+")[0];      //java 正则表达式
                        datasContent.add(reds);
                        count++;
                    }
                }
                for (int i = 0; i < datasContent.size(); i++) {
                    sendStateList.put(i, " ");
                    receiveList.put(i, " ");
                }
                isr.close();
                br.close();
            } else {
                Toast.makeText(getApplicationContext(), "找不到文件", Toast.LENGTH_SHORT).show();//找不到文件情况下
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        sendAsyncTask=new SendAsyncTask();
        sendAsyncTask.execute();
    }

    public void SenMsg(int i) {
        split = datasContent.get(i).split("\\*\\*\\*");
        number = split[0];
        message = split[1];

        Intent sentIntent = new Intent(SENT_SMS_ACTION);
        sentIntent.putExtra("SEND_SMS_NUM", number);
        sentIntent.putExtra("INDEX", i);
        sentIntent.putExtra("SEND_SMS_CONTENT", message);
        PendingIntent sentPI = PendingIntent.getBroadcast(this, i, sentIntent, i);
        // create the deilverIntent parameter
        Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
        deliverIntent.putExtra("SEND_SMS_NUM", number);
        deliverIntent.putExtra("INDEX", i);
        deliverIntent.putExtra("SEND_SMS_CONTENT", message);
        PendingIntent deliverPI = PendingIntent.getBroadcast(this, i, deliverIntent, i);
        // 如果短信内容超过70个字符 将这条短信拆成多条短信发送出去
        if (message.length() > 70) {
            ArrayList<String> msgs = smsManager.divideMessage(message);
            for (String msg : msgs) {
                smsManager.sendTextMessage(number, null, msg, sentPI, deliverPI);
            }
        } else {
            smsManager.sendTextMessage(number, null, message, sentPI, deliverPI);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastSend);
//        unregisterReceiver(broadcastReceiver);
    }
    public void getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            while ((line = bufReader.readLine()) != null) {
                if (!"".equals(line)) {
                    String temp1 = EncodingUtils.getString(line.getBytes("utf-8"), "utf-8");
                    String reds = temp1.split("\\+")[0];      //java 正则表达式
                    datasContent.add(reds);
                    count++;
                }
            }
            mAdapter = new SMSAdapter(this, datasContent, sendStateList, receiveList);
            listview.setAdapter(mAdapter);
            inputReader.close();
            bufReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //在异步方法中 调用
    private class SmsAsyncTask extends AsyncTask<String, Void, String> {
        long curDate = 0;

        @Override
        protected void onPreExecute() {
            progressbar.setVisibility(View.VISIBLE);
            curDate = new Date(System.currentTimeMillis()).getTime();
        }

        @Override
        protected String doInBackground(String... strings) {
            getTextData();
            return null;
        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(String s) {
            long endData = new Date(System.currentTimeMillis()).getTime();
            long diffTime = endData - curDate;
            mAdapter = new SMSAdapter(MainActivity.this, datasContent, null, null);
            listview.setAdapter(mAdapter);
            progressbar.setVisibility(View.GONE);
            Log.e("time", "time::" + diffTime + "\t\tlist条目" + count);
        }

        @Override
        protected void onCancelled() {
            progressbar.setVisibility(View.GONE);
        }
    }

    private class SendAsyncTask extends   AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            progressbar.setVisibility(View.VISIBLE);
            tvWait.setVisibility(View.VISIBLE);
        }
        @Override
        protected String doInBackground(String... strings) {
            //全部发送
            for (int i = 0; i < datasContent.size(); i++) {
                SenMsg(i);
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            tvWait.setVisibility(View.GONE);
//            progressbar.setVisibility(View.GONE);
            Toast.makeText(MainActivity.this, "发送完成", Toast.LENGTH_SHORT).show();
            tvWait.setVisibility(View.VISIBLE);
            tvWait.setText("正在查询发送状态");
        }
    }
}